/**
 * Copyright(c) 2010 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-5-19 下午1:19 Created by lyyang
 */
package com.jade.framework.web.security;

import java.security.Principal;

import com.jade.framework.base.security.PrincipalCapsule;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;

/**
 * 权限拦截器
 *
 * @author lyyang
 * @version 1.0 13-5-19 下午1:19
 */
public class PrincipalArgumentResolver
        implements WebArgumentResolver
{
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest nativeWebRequest)
            throws Exception
    {
        if (methodParameter.getParameterType().equals(PrincipalCapsule.class)) {
            Principal principal = (Principal) nativeWebRequest.getAttribute("principal",
                    RequestAttributes.SCOPE_SESSION);
            if (principal == null) {
                principal = nativeWebRequest.getUserPrincipal();
                nativeWebRequest.setAttribute("principal", principal, RequestAttributes.SCOPE_SESSION);
            }
            if (principal == null) {
                return null;
            }
            else {
                return new PrincipalCapsule(principal);
            }
        }
        return UNRESOLVED;
    }
}
